import tkinter as tk
from tkinter import ttk

class RegisterTable(ttk.Frame):
    """寄存器表格视图"""

    def __init__(self, parent, controller):
        super().__init__(parent)
        self.controller = controller

        # 创建表格
        self.create_widgets()

        # 初始更新
        self.update_table()

    def create_widgets(self):
        """创建控件"""
        # 创建表格框架
        table_frame = ttk.LabelFrame(self, text="寄存器地址映射表")
        table_frame.pack(fill=tk.BOTH, expand=True, padx=5, pady=5)

        # 创建表格
        columns = ("地址", "名称", "值", "单位", "类型")
        self.tree = ttk.Treeview(table_frame, columns=columns, show="headings")

        # 设置列
        self.tree.column("地址", width=80, anchor=tk.CENTER)
        self.tree.column("名称", width=150, anchor=tk.W)
        self.tree.column("值", width=100, anchor=tk.CENTER)
        self.tree.column("单位", width=80, anchor=tk.CENTER)
        self.tree.column("类型", width=80, anchor=tk.CENTER)

        # 设置标题
        for col in columns:
            self.tree.heading(col, text=col)

        # 添加滚动条
        scrollbar = ttk.Scrollbar(table_frame, orient=tk.VERTICAL, command=self.tree.yview)
        self.tree.configure(yscroll=scrollbar.set)

        # 布局
        scrollbar.pack(side=tk.RIGHT, fill=tk.Y)
        self.tree.pack(side=tk.LEFT, fill=tk.BOTH, expand=True)

    def update_table(self, registers=None):
        """更新表格数据"""
        # 清空现有数据
        for item in self.tree.get_children():
            self.tree.delete(item)

        # 获取寄存器数据
        if registers is None:
            registers = self.controller.get_registers()

        # 添加新数据
        for reg in registers:
            self.tree.insert("", tk.END, values=(
                f"0x{reg.address:04X}",
                reg.name,
                reg.formatted_value(),
                reg.unit,
                reg.data_type
            ))
            